﻿namespace Numbrella.Client
{
	using System;
	using System.Collections.Generic;
	using System.Diagnostics;
	using System.Reflection;
	using Numbrella.Interaction;

	public class MarshalByRefTaskPerformProxy : MarshalByRefObject
	{
		private readonly HashSet<Assembly> loadedAssemblies = new HashSet<Assembly>();

		public void LoadAssembly(byte[] rawAssembly)
		{
			Assembly assembly = Assembly.Load(rawAssembly);
			if (!this.loadedAssemblies.Contains(assembly))
			{
				ResolveEventHandler handler = (sender, e) => e.Name == assembly.FullName ? assembly : null;
				AppDomain.CurrentDomain.AssemblyResolve += handler;
				this.loadedAssemblies.Add(assembly);
			}
		}

		public ITaskResult PerformTask(ITask task)
		{
			Debug.Assert(task != null, "Task should not be null.");
			return task.Perform();
		}
	}
}